package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper; //日志表

    @Autowired
    private AnalysisMapper analysisMapper; //统计表

    /**
     * 计算日志表中的数据，保存或者更新到统计表中
     */
    public void analysis() throws ParseException {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterDay = DateUtil.yesterday().toString("yyyy-MM-dd");
        //1、查询数据
        //1.1 新注册用户数
        Integer regNum = logMapper.queryByLogTimeAndType("0102", today);
        //1.2 活跃用户数
        Integer actNum = logMapper.queryByLogTime(today);
        //1.3 登陆次数
        Integer logNum = logMapper.queryByLogTimeAndType("0101", today);
        //1.4 次日留存用户数
        Integer retNum = logMapper.queryNumRetention1d(today, yesterDay);
        //2、根据统计日志查询数据
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        qw.eq("record_date",today);
        Analysis analysis = analysisMapper.selectOne(qw);
        //3、判断数据是否存在
        if(analysis == null) {
            //3.1 数据不存在，保存
            analysis = new Analysis();
            analysis.setNumLogin(logNum);
            analysis.setNumActive(actNum);
            analysis.setNumRegistered(regNum);
            analysis.setNumRetention1d(retNum);
            analysis.setCreated(new Date());
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(today)); //日期
            analysisMapper.insert(analysis);
        }else {
            //3.2 数据存在，更新
            analysis.setNumLogin(logNum);
            analysis.setNumActive(actNum);
            analysis.setNumRegistered(regNum);
            analysis.setNumRetention1d(retNum);
            analysisMapper.updateById(analysis);
        }
    }
}

